package com.example.demo.controller;

import com.example.demo.dto.LoginRequest;
import com.example.demo.entity.Account;
import com.example.demo.service.AccountService;
import com.example.demo.util.RestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @PostMapping("/login")
    public RestBean<Account> login(@RequestBody LoginRequest request) {
        Account account = accountService.login(request.getUsername(), request.getPassword());
        return account != null ?
                RestBean.success(account, "登录成功") :  // 先传数据对象，再传消息
                RestBean.failure(401, "用户名或密码错误");
    }

    @GetMapping("/current-user")
    public RestBean<Account> getCurrentUser(@AuthenticationPrincipal UserDetails userDetails) {
        Account account = accountService.findAccountByUsername(userDetails.getUsername());
        return RestBean.success(account);
    }
}